﻿<template>
	<div class="flowSystemSGJK-container">
		<!-- //Code Gen QueryStart !don't delete -->
		<el-collapse accordion v-model="activeName">
			<el-collapse-item name="1">
				<template #title>
					<el-tag effect="light" type="warning" round>功能面板</el-tag><el-icon class="header-icon ml12">
						<info-filled />
					</el-icon>
				</template>
				<el-form :model="queryParams" ref="queryForm" :inline="true"
					v-if="props.info.id==undefined||props.info.id<=0" class="mt8 ml2">
					<el-form-item label="关键字">
						<el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字"
							@keyup.enter.native="handleQuery" />

					</el-form-item>
					<el-form-item label="工程名稱">
						<el-input v-model="queryParams.project_name" clearable="" placeholder="请输入工程名稱"
							@keyup.enter.native="handleQuery" />

					</el-form-item>
					<el-form-item label="承攬廠商名稱">
						<el-input v-model="queryParams.supplier_name" clearable="" placeholder="请输入承攬廠商名稱"
							@keyup.enter.native="handleQuery" />

					</el-form-item>
					<el-form-item label="施工開始時間">
						<el-date-picker placeholder="请选择施工開始時間" type="datetimerange"
							v-model="queryParams.beginDateTimeRange" />

					</el-form-item>
					<el-form-item label="施工結束時間">
						<el-date-picker placeholder="请选择施工結束時間" type="datetimerange"
							v-model="queryParams.endDateTimeRange" />

					</el-form-item>
					<el-form-item label="施工人员信息">
						<el-input v-model="queryParams.personlist" clearable="" placeholder="请输入施工人员信息"
							@keyup.enter.native="handleQuery" />

					</el-form-item>
					<el-form-item>
						<el-button-group>
							<el-button type="primary" icon="ele-Search" @click="handleQuery"
								v-auth="'flowSystemSGJK:page'"> 查询 </el-button>
							<el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>

						</el-button-group>

					</el-form-item>
				</el-form>
				<el-col :span="24">
					<!-- //Code Gen Start Button1 !don't delete -->
					<el-form-item>

					</el-form-item>
					<!-- //Code Gen End Button1 !don't delete -->
				</el-col>

			</el-collapse-item>
		</el-collapse>
		<!-- //Code Gen QueryEnd !don't delete -->
		<el-card class="full-table" shadow="hover" style="margin-top: 8px">
			<el-table :data="tableData" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id"
				border="" ref="multipleTableRef" :row-class-name="tableRowClassName" @sort-change="(column)=>{
				  tableParams.order =column.order;
				  tableParams.field =column.prop;
				  handleQuery();
				}" :row-style="rowStyleDisplay" show-summary @select-all="(checkList)=>{
					multipleSelection=checkList;
				}" :summary-method="getSummaries" :cell-style="handleChangeCellStyle" @select="handleSelectionChange"
				:expand-row-keys="expandList" @expand-change="handleExpandChange">
				<el-table-column type="selection" align="center" :selectable="checkTable" />
			<!-- 	<el-table-column type="index" label="序号" width="55" align="center">
					<template #default="scope">
					</template>
				</el-table-column> -->
				<el-table-column fixed="left" :sortable="sortTableCheck('')" align="center" prop="project_name" label="工程名稱"
					width="180" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column fixed="left" :sortable="sortTableCheck('')" align="center" prop="supplier_name" label="承攬廠商名稱"
					width="150" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="req_dept" label="工程主辦部門" width="90"
					show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="req_dept_name" label="工程主辦部門名稱"
					width="120" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="req_empl" label="工程主辦人員" width="90"
					show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="req_empl_name" label="工程主辦人員姓名"
					width="120" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="req_tel" label="緊急聯絡電話" width="90"
					show-overflow-tooltip="">
				</el-table-column>
				<el-table-column fixed="left" :sortable="sortTableCheck('')" align="center" prop="beginDateTime" label="施工開始時間"
					width="130" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column fixed="left" :sortable="sortTableCheck('')" align="center" prop="endDateTime" label="施工結束時間"
					width="130" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="content_desc" label="施工內容說明"
					width="90" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="personlist" label="施工人员信息"
					width="90" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="reqDateTime" label="申請時間"
					width="140" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="content" label="详细内容" width="140"
					show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="progress" label="工作进度" width="140"
					show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="changeProject" label="待改善项目"
					width="140" show-overflow-tooltip="">
				</el-table-column>
				<el-table-column :sortable="sortTableCheck('')" align="center" prop="images" label="照片" width="140"
					show-overflow-tooltip="">
					<template #default="scope">
						<el-image v-for="item in JSON.parse(scope.row.images)"
							style="width: 60px; height: 60px; margin-left: 5px;" :src="item.url" :lazy="true"
							:hide-on-click-modal="true" :preview-src-list="[item.url]" :initial-index="0"
							fit="scale-down" preview-teleported="" />

					</template>
				</el-table-column>
				<!-- //Code Gen Start Button2 !don't delete -->
				<el-table-column label="操作" :width="getWidthByAuths(['flowSystemSGJK:edit','flowSystemSGJK:printLog'])"
					align="center" fixed="right" show-overflow-tooltip=""
					v-if="auths(['flowSystemSGJK:edit','flowSystemSGJK:printLog'])">
					<template #default="scope">
						<!-- <el-button  icon="ele-StarFilled" size="small" text="" type="primary"   @click="openprintLog(scope.row)" v-auth="'flowSystemSGJK:printLog'">監控日誌打印</el-button> -->
						<el-button type="warning" icon="ele-Edit" @click="openEditFlowSystemSGJK(scope.row)"
							v-auth="'flowSystemSGJK:printLog'">監工日誌打印</el-button>

					</template>
				</el-table-column>
				<!-- //Code Gen End Button2 !don't delete -->
			</el-table>
			<el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize"
				:total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200]" small="" background=""
				@size-change="handleSizeChange" @current-change="handleCurrentChange"
				layout="total, sizes, prev, pager, next, jumper" />
			<!-- 上面分页加上这个字符串就居中显示了 ->, -->
			<editDialog ref="editDialogRef" :title="editFlowSystemSGJKTitle" @printJKLog="printJKLog" />
			<printLog title="監控日誌打印" :key="timer" ref="printLogRef" @reloadTable="handleQuery" />
		</el-card>

		<el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px"
			append-to-body="true">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
						<ele-UploadFilled /> </el-icon>
					<span> 上传文件 </span>
				</div>
			</template>
			<div>
				<el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList" action=""
					:on-change="handleChange" accept=".xls,.xlsx">
					<el-icon class="el-icon--upload">
						<ele-UploadFilled />
					</el-icon>
					<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
					<template #tip>
						<div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
					</template>
				</el-upload>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dialogUploadVisible = false">取消</el-button>
					<el-button type="primary" @click="uploadFile">确定</el-button>
				</span>
			</template>
		</el-dialog>

		<el-dialog v-model="state.dialogInfoVisible" draggable width="1000px" append-to-body="true">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle">
						<ele-Document /> </el-icon>
					<span>详情</span>
				</div>
			</template>
			<json-viewer :value="JSON.parse(state.dialogInfoContent)" :expand-depth="8" copyable boxed
				sort></json-viewer>
		</el-dialog>

	</div>
</template>

<script lang="ts" setup="" name="flowSystemSGJK">
	import { InfoFilled } from '@element-plus/icons-vue';
	import { ref, reactive, onMounted, nextTick } from "vue";
	import { useRoute } from 'vue-router';
	import { ElMessageBox, ElMessage, UploadInstance } from "element-plus";
	import _ from 'lodash';
	import { auth, getWidthByAuths, auths } from '/@/utils/authFunction';
	import { downloadByData, getFileName } from '/@/utils/download';
	//import { formatDate } from '/@/utils/formatTime';

	import editDialog from '/@/views/main/flowSystemSGJK/component/editDialog.vue'
	import printLog from '/@/components/common/printData.vue'

	import { pageFlowSystemSGJK, saveFlowSystemSGJK, deleteFlowSystemSGJK, exportFlowSystemSGJKExcel, importUrl, downLoadTemplate } from '/@/api/main/flowSystemSGJK';
	import { SysFile } from '/@/api-services/models';
	import request from '/@/utils/request';
	const uploadRef = ref<UploadInstance>();
	const state = reactive({
		loading: false,
		fileData: [] as Array<SysFile>,
		queryParams: {
			fileName: undefined,
			startTime: undefined,
			endTime: undefined,
		},
		tableParams: {
			page: 1,
			pageSize: 10,
			total: 0 as any,
		},
		dialogUploadVisible: false,
		dialogPdfVisible: false,
		dialogInfoVisible: false,
		dialogInfoContent: '',
		fileList: [] as any,
		pdfUrl: '',
	});
	const activeName = ref('1');
	const timer = ref<any>();
	const expandList = ref<any>([]);
	const editDialogRef = ref();
	const printLogRef = ref();
	const loading = ref(false);
	const tableData = ref<any>([]);
	const multipleTableRef = ref<InstanceType<typeof ElTable>>();
	const multipleSelection = ref<any>([]);
	const toggleSelection = (rows ?: []) => {
		multipleTableRef.value.clearSelection()
	}
	const queryParams = ref<any>({});
	const tableParams = ref({
		page: 1,
		pageSize: 10,
		total: 0,
		frontPath: null
	});
	const editFlowSystemSGJKTitle = ref("");
	const currenTab = ref<any>({});
	const tabOption = null;

	var props = defineProps({
		info: {
			default: {},
		},
	});
	// 页面加载时
	onMounted(async () => {
		const route = useRoute();
		tableParams.value.frontPath = route.path;
		handleQuery();
		if (tabOption != null) {
			currenTab.value = tabOption.column[0];
		}

	});
	//是否能排序
	const sortTableCheck = (icCanSort) => {
		if (icCanSort != null && icCanSort != "" && icCanSort == "Y")
			return true;
		else
			return false;
	};

	const selectAfter = () => {
		nextTick(() => {
		});
	}
	//页签切换
	const handleTabChange = (column) => {
		currenTab.value = column;
		selectAfter();
	}
	// 勾选框是否禁用

	const checkTable = (row, index) => {
		if (row.id) {
			return true; //不禁用
		}
		return false; //禁用
	};

	//行颜色
	const tableRowClassName = (every) => {
	}

	// 打开上传页面
	const openUploadDialog = () => {
		state.fileList = [];
		state.dialogUploadVisible = true;
	};

	// 通过onChanne方法获得文件列表
	const handleChange = (file : any, fileList : []) => {
		state.fileList = fileList;
	};

	//保存行编辑的数据
	const saveData = _.debounce(async function (row) {
		await saveFlowSystemSGJK(row);
		await handleQuery();
	}, 1000);


	// 查看详情
	const viewDetail = _.throttle(async (row : any, tableName : string, id : number) => {
		var url = `api/flowSystemSGJK/Info/${tableName}/${id}`
		var res = await request({ url: url, method: 'get' });
		state.dialogInfoContent = res.data.result;
		state.dialogInfoVisible = true;
	}, 1000);

	// 上传
	const uploadFile = async () => {
		if (state.fileList.length < 1) return;
		var url = importUrl();

		var formData = new window.FormData();
		formData.append('file', state.fileList[0].raw);
		var res = await request(
			{
				url: url,
				method: 'post',
				data: formData,
				headers: { 'Content-Type': 'multipart/form-data' }
			}
		)
		ElMessage.success('上传成功');
		await handleQuery();
		state.dialogUploadVisible = false;
	};

	//导出
	const exportFlowSystemSGJK = async () => {
		var res = await exportFlowSystemSGJKExcel(queryParams.value);
		var fileName = getFileName(res.headers);
		downloadByData(res.data as any, fileName);
	};

	//下载模板
	const downLoadTemplate = async () => {
		var url = downLoadTemplate();
		var res = await request({
			url: url,
			method: 'get',
			responseType: 'blob'
		});
		var fileName = getFileName(res.headers);
		downloadByData(res.data as any, fileName);
	}


	// 查询操作
	const handleQuery = async (parentArgument : any) => {
		timer.value = new Date().getTime();
		loading.value = true;
		if (props.info.id > 0) {
			//Code Gen Start !don't delete 
			queryParams.value.$TemplateField = props.info.id; //展开行对应的id赋值
			//Code Gen End !don't delete 
		}
		if (parentArgument != null && parentArgument != undefined) {
			if (parentArgument.id == -1) {
				queryParams.value.wCode = parentArgument.id; //此页作为组件，parentArgument父组件传过来的值
			} else {
				queryParams.value.wCode = parentArgument.wCode; //此页作为组件，parentArgument父组件传过来的值
			}
		}
		var res = await pageFlowSystemSGJK(Object.assign(queryParams.value, tableParams.value));
		tableData.value = res.data.result?.items ?? [];
		tableParams.value.total = res.data.result?.total;
		loading.value = false;
	};

	// 打开新增页面
	const openAddFlowSystemSGJK = () => {
		editFlowSystemSGJKTitle.value = '添加工程監工日誌打印';
		editDialogRef.value.openDialog({});
	};

	// 打开编辑页面
	const openEditFlowSystemSGJK = (row : any) => {
		editFlowSystemSGJKTitle.value = '编辑工程監工日誌打印';
		editDialogRef.value.openDialog(row);
	};

	const openprintLog = _.debounce((row : any) => {
		var str = '工程監工日誌V1';

		if (row.images != null) {
			var imgs = JSON.parse(row.images);

			console.log(imgs.length);
			if (imgs.length >= 1)
				str = '工程監工日誌V1';
			 if (imgs.length >= 2)
				str = '工程監工日誌V2';
			 if (imgs.length >= 3)
				str = '工程監工日誌V3';
			 if (imgs.length >= 4) {
				str = '工程監工日誌V4';
			}
		}
		printLogRef.value.commentClick(str, 0, [row]);

	}, 1000);


	const printJKLog = async (row) => {

		openprintLog(row);
		await handleQuery();
	}

	const showKeyValueInfo = (list) => {
		if (list != null && list.length > 0) {
			if (list[0].label != undefined) {
				return list.map(r => r.label)
			}
		}
		return list;
	}


	const handleExpandChange = (row : any, expandedRows : any) => {
		timer.value = new Date().getTime();
		if (expandedRows.length) {
			expandList.value = [];
			if (row) {
				expandList.value.push(row.id);
			}
		} else {
			expandList.value = [];
		}
	};

	// 删除
	const delFlowSystemSGJK = (row : any) => {
		ElMessageBox.confirm(`确定要删除吗?`, "提示", {
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning",
		})
			.then(async () => {
				await deleteFlowSystemSGJK(row);
				handleQuery();
				ElMessage.success("删除成功");
			})
			.catch(() => { });
	};

	// 改变页面容量
	const handleSizeChange = (val : number) => {
		tableParams.value.pageSize = val;
		handleQuery();
	};

	// 改变页码序号
	const handleCurrentChange = (val : number) => {
		tableParams.value.page = val;
		handleQuery();
	};


	const handleSelectionChange = (val : []) => {
		multipleSelection.value = val
		if (val.length > 1) {
			let del_row = val.shift();
			multipleTableRef.value.toggleRowSelection(del_row, false);
		}
		multipleSelection.value = multipleSelection.value[0];
		selectAfter();
	}







	//修改行颜色
	const rowStyleDisplay = ({ row, rowIndex }) => {
		return null;
	};
	//修改列颜色	
	const handleChangeCellStyle = ({ row, column, rowIndex, columnIndex }) => {

	}


	//显示合计
	interface SummaryMethodProps<T = Product> {
		columns : TableColumnCtx<T>[]
		data : T[]
	}
	const getSummaries = (param : SummaryMethodProps) => {
		const { columns, data } = param
		const sums : string[] = []
		columns.forEach((column, index) => {
			var needCollectFileds = [];
			if (needCollectFileds.length <= 0)
				return;

			if (index === 0) {
				sums[index] = '汇总'
				return
			}
			if (needCollectFileds.indexOf(column.property) < 0) {
				return;
			}


			const values = data.map((item) => Number(item[column.property]))
			if (!values.every((value) => Number.isNaN(value))) {
				sums[index] = `合计: ${values.reduce((prev, curr) => {
					const value = Number(curr)
					if (!Number.isNaN(value)) {
						return prev + curr
					} else {
						return prev
					}
				}, 0)}`
			} else {
				sums[index] = ""
			}
		})

		return sums
	}





	//将属性或者函数暴露给父组件
	defineExpose({ handleQuery });
</script>
<style scoped lang='scss'>
	@import url('../../../../public/css/iconfont.css');
	@import url('../../../../public/css/iconshine.css');
	@import url('../../../../public/css/linecolor.css');

	/* 隐藏全选按钮 */
	::v-deep .el-table th.el-table__cell:nth-child(1) .cell {
		visibility: hidden;
	}
</style>